/**
 * JAVACC DEMO 1.0
 */
package com.apache.uct.service.plugins;

import com.apache.database.constant.SpringContextLoader;
import com.apache.database.constant.SystemTools;
import com.apache.database.constant.Validator;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.uct.common.entity.Act;
import com.apache.uct.common.entity.Role;
import com.apache.uct.common.entity.RoleGive;
import com.apache.uct.common.vo.ActVo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:
 *
 * @author Hou Dayu 创建时间：2016-5-13
 */
public class ActCacheHelper {

    private static ActCacheHelper instance;

    private IDao cacheUctDao;

    private ActCacheHelper() {
    }

    public static ActCacheHelper getInstance() {
        if (null == instance) {
            instance = new ActCacheHelper();
        }
        return (instance);
    }

    /**
     * description:  添加用户角色关系缓存信息
     */
    @SuppressWarnings("unchecked")
    public void writeRoleUser(String userId, String roleId, boolean isWrite) {
        String key = "roleUser_" + userId;
        List<String> list = (List<String>) SystemTools.getInstance().getCache("")
                .getCacheObjectByKey(key);
        if (isWrite) {
            if (Validator.isEmpty(list)) {
                list = getInfoList(1, "userId", userId, RoleGive.class.getName());
                if (null == list)
                    list = new ArrayList<String>();
            }
            if (!list.contains(roleId)) {
                list.add(roleId);
            }
            SystemTools.getInstance().getCache("").createCacheObject(key, list);
        } else {
            if (!Validator.isEmpty(list)) {
                list.remove(roleId);
                SystemTools.getInstance().getCache("").createCacheObject(key, list);
            }
        }
    }

    /**
     * description:  用户删除时删除用户角色关系缓存信息
     */
    public void delRoleUserByUserId(String userId) {
        String key = "roleUser_" + userId;
        SystemTools.getInstance().getCache("").removeCacheObject(key);
    }

    /**
     * description:  按用户ID获取权限信息
     */
    @SuppressWarnings("unchecked")
    public Map<String, String> getActMapByUserId(String userId) {
        String key = "user_act_" + userId;
        Map<String, String> result = new HashMap<String, String>();
        Map<String, String> rmps = getActMapRoleByUserId(userId);
        if (!Validator.isEmpty(rmps)) {
            result.putAll(rmps);
            Map<String, String> ump = (Map<String, String>) SystemTools.getInstance().getCache("")
                    .getCacheObjectByKey(key);
            if (!Validator.isEmpty(ump))
                result.putAll(ump);
        }
        return result;
    }

    /**
     * description:  按角色ID获取权限信息
     */
    @SuppressWarnings("unchecked")
    public Map<String, String> getActMapRoleByUserId(String userId) {
        String key = "roleUser_" + userId;
        List<String> list = (List<String>) SystemTools.getInstance().getCache("")
                .getCacheObjectByKey(key);
        if (Validator.isEmpty(list)) {
            list = getInfoList(1, "userId", userId, RoleGive.class.getName());
            if (!Validator.isEmpty(list)) {
                return null;
                //				for (String roleId : list) {
                //					List<Act> lista = getInfoMap(roleId, "role", Act.class.getName());
                //					Map<String, String> actMap = new HashMap<String, String>();
                //					if (!Validator.isEmpty(lista)) {
                //						for (Act act : lista) {
                //							actMap.put(act.getActId(), act.getFullEname() + ";" + act.getActUrl());
                //						}
                //						SystemTools.getInstance().getCache("").createCacheObject("role_act_" + roleId, actMap);
                //						actAllCache(roleId, "role");
                //					}
                //				}
            }
        }
        if (!Validator.isEmpty(list)) {
            Map<String, String> result = new HashMap<String, String>();
            for (int i = 0; i < list.size(); i++) {
                String rkey = "role_act_" + list.get(i);
                Map<String, String> rmp = (Map<String, String>) SystemTools.getInstance()
                        .getCache("").getCacheObjectByKey(rkey);
                if (!Validator.isEmpty(rmp))
                    result.putAll(rmp);
            }
            return result;
        }
        return null;
    }

    /**
     * description:  添加权限缓存
     */
    @SuppressWarnings("unchecked")
    public synchronized void writeCache(String objId, String actGiveType, String actId,
            String actFullEname, boolean isWrite) {
        if ("org".equals(actGiveType) || "dept".equals(actGiveType)) {//对部门或权构授权不记缓存
            return;
        }
        String key = actGiveType + "_act_" + objId;
        Map<String, String> actMap = (Map<String, String>) SystemTools.getInstance().getCache("")
                .getCacheObjectByKey(key);
        if (isWrite) {
            if (Validator.isEmpty(actMap)) {
                actMap = new HashMap<String, String>();
                List<Act> list = getInfoMap(objId, actGiveType, Act.class.getName());
                if (!Validator.isEmpty(list)) {
                    for (Act act : list) {
                        actMap.put(act.getActId(), act.getFullEname() + ";" + act.getActUrl());
                    }
                }
            }
            actMap.put(actId, actFullEname);
            SystemTools.getInstance().getCache("").createCacheObject(key, actMap);
            actAllCache(objId, actGiveType);
        } else {
            if (!Validator.isEmpty(actMap)) {
                actMap.remove(actId);
                SystemTools.getInstance().getCache("").createCacheObject(key, actMap);
            }
        }
    }

    /**
     * description:  记录所有权限的缓存ID
     */
    @SuppressWarnings("unchecked")
    private void actAllCache(String objId, String actGiveType) {
        String key = "sysActall_Cache";
        List<String> list = (List<String>) SystemTools.getInstance().getCache("")
                .getCacheObjectByKey(key);
        if (Validator.isEmpty(list)) {
            list = new ArrayList<String>();
        }
        String value = actGiveType + "_act_" + objId;
        if (!list.contains(value)) {
            list.add(value);
            SystemTools.getInstance().getCache("").createCacheObject(key, list);
        }
    }

    /**
     * description:  删除权限缓存
     */
    public void delCache(String objId, String actGiveType) {
        if ("user".equals(actGiveType) || "role".equals(actGiveType)) {
            String key = actGiveType + "_" + objId;
            SystemTools.getInstance().getCache("").removeCacheObject(key);
        }
    }

    /**
     * description:  删除所有权限缓存
     */
    public void delActCacheAll() {
        Thread t = new Thread() {

            public void run() {
                String key = "sysActall_Cache";
                List<String> list = (List<String>) SystemTools.getInstance().getCache("")
                        .getCacheCloneByKey(key);
                if (!Validator.isEmpty(list)) {
                    int count = list.size();
                    for (int i = 1; i <= count; i++) {
                        SystemTools.getInstance().getCache("").removeCacheObject(list.get(i));
                    }
                }
            }
        };
        t.start();
    }

    public void writeUserActCache(String userId, List<ActVo> actList) {
        Runnable r = new UserActCache(actList, userId);
        Thread t = new Thread(r);
        t.start();
    }

    public List<Role> getRolesForUserEname(String userEname) {
        MethodParam param = new MethodParam("ByUserEname", "", "", Role.class.getName());
        param.setParams("userEname", userEname);
        return getCacheUctDao().select(param);
    }

    private class UserActCache implements Runnable {

        private List<ActVo> actList;

        private String userId;

        public UserActCache(List<ActVo> actList, String userId) {
            this.actList = actList;
            this.userId = userId;
        }

        public void run() {
            int count = actList.size();
            for (int i = 1; i < count; i++) {
                ActVo act = actList.get(i);
                if ("role".equalsIgnoreCase(act.getGiveType())) {
                    String key = "roleUser_" + userId;
                    List<String> list = (List<String>) SystemTools.getInstance().getCache("")
                            .getCacheObjectByKey(key);
                    if (Validator.isEmpty(list)) {
                        list = new ArrayList<String>();
                        list.add(act.getRoleId());
                    } else {
                        if (!list.contains(act.getRoleId())) {
                            list.add(act.getRoleId());
                        }
                    }
                    SystemTools.getInstance().getCache("").createCacheObject(key, list);
                }
                ActCacheHelper.getInstance()
                        .writeCache(act.getRoleId(), act.getGiveType(), act.getActId(),
                                act.getFullEname() + ";" + act.getActUrl(), true);
            }
        }
    }

    private List<String> getInfoList(int type, String key, String value, String spaceName) {
        MethodParam param = new MethodParam("CacheByObjId", "", getCacheUctDao().getSql(type),
                spaceName);
        param.setParams(key, value);
        return getCacheUctDao().select(param);
    }

    private List<Act> getInfoMap(String objId, String giveType, String spaceName) {
        MethodParam param = new MethodParam("CacheByObjId", "", getCacheUctDao().getSql(2),
                spaceName);
        param.setParams("roleId", objId);
        param.setParams("giveType", giveType);
        return getCacheUctDao().select(param);
    }

    public IDao getCacheUctDao() {
        if (null == cacheUctDao) {
            cacheUctDao = (IDao) SpringContextLoader.getBean("cacheUctDao");
        }
        return cacheUctDao;
    }

}
